package com.android.huimeiqupin.fragment.group;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.huimeiqupin.R;
import com.android.huimeiqupin.activity.GoodsDetailActivity;
import com.android.huimeiqupin.adapt.MainListSortKillAdapt;
import com.android.huimeiqupin.fragment.BaseLazyFragment;
import com.android.huimeiqupin.model.group.SortHeadThumbData;
import com.android.huimeiqupin.model.group.SortHeadThumbDataCallback;
import com.android.huimeiqupin.model.group.SortKillData;
import com.android.huimeiqupin.model.group.SortKillDataCallback;
import com.android.huimeiqupin.utils.ConstantsUrl;
import com.android.huimeiqupin.utils.HttpUtils;
import com.android.huimeiqupin.utils.MyLog;
import com.android.huimeiqupin.utils.ObjectUtils;
import com.android.huimeiqupin.view.group.VRefreshLayout;
import com.android.huimeiqupin.view.recycleview.CustomLoadMoreView;
import com.android.huimeiqupin.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 热搜页
 * ---------------------------------------
 */
public class Fragment_TabKillList extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    VRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;

    private View rootView;
    private static final String ARG_PARAM1 = "param1";
    private String mParam1;
    private FragmentActivity mcontext;
    private MainListSortKillAdapt adapter;
    private LayoutInflater inflater;
    private int page = 1;
    private boolean networkConnected;
    private View header;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }
    }

    public static Fragment_TabKillList newInstance(String position) {
        Fragment_TabKillList fragment = new Fragment_TabKillList();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initPrepare() {
        ReFreshData();
    }

    private void initRecycle() {
        adapter = new MainListSortKillAdapt(R.layout.item_list_sort_kill, null);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        adapter.addHeaderView(header);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop((ImageView) rootView.findViewById(R.id.top), 0);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                Intent intent = new Intent(mcontext, GoodsDetailActivity.class);
                SortKillData.SortXianshiData.ListBean listBean = adapter.getItem(position);
                int end = Integer.parseInt(listBean.getEnd_time());
                int start = Integer.parseInt(listBean.getStart_time());
                int run = listBean.getRun_time();
                if (run > end && run > start) {
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW, 5);
                } else if (run > start && run < end) {
                    if (listBean.getScale() == 100) {
                        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW, 4);
                    } else {
                        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW, 1);
                    }
                } else if (run < start) {
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW, 3);
                }
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID, listBean.getId());
                startActivity(intent);
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.item_list_sort_kill_kai_ll:
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
                        break;
                }
                return false;
            }
        });
    }

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            GetHeadImageData();
            GetListData(page, mParam1);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        rootView = inflater.inflate(R.layout.layout_recycle_refresh, container, false);
        mcontext = getActivity();
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        ButterKnife.bind(this, rootView);
        mainTopBg.setVisibility(View.GONE);
        initUI();
        return rootView;
    }

    private void initUI() {
        header = inflater.inflate(R.layout.item_list_sort_dapai, null, false);
        header.findViewById(R.id.ll_msg).setVisibility(View.VISIBLE);
        initRecycle();
    }

    private void ReFreshData() {
        if (mRefreshLayout != null) {
            mRefreshLayout.setBackgroundColor(Color.TRANSPARENT);
            mRefreshLayout.setAutoRefreshDuration(400);
            mRefreshLayout.setRatioOfHeaderHeightToReach(1.5f);
            mRefreshLayout.addOnRefreshListener(new VRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                page = 1;
                                GetHeadImageData();
                                GetListData(page, mParam1);
                                mRefreshLayout.refreshComplete();
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                    }
                }
            });
        }
    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                GetHeadImageData();
                GetListData(page, mParam1);
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetListData(page, mParam1);
    }

    //获取数据
    private void GetListData(final int page, String type) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MAINLIST_XIANSHI + "?page=" + page + type;
        MyLog.e("address", "" + address);
        if (networkConnected) {
            HttpUtils.get(address, null, new SortKillDataCallback() {

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                        }

                        @Override
                        public void onResponse(SortKillData response, int id) {
                            if (response == null) {
                                ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                                return;
                            }
                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);

                            if (response.getCode() == 0) {
                                SortKillData.SortXianshiData data = response.getData();
                                if (data == null || !ObjectUtils.listHasData(data.getList())) {
                                    if (page == 1) {
                                        noData.setVisibility(View.VISIBLE);
                                    } else {
                                        adapter.loadMoreEnd();
                                    }
                                    return;
                                }
                                ArrayList<SortKillData.SortXianshiData.ListBean> listdata = new ArrayList<>();
                                listdata.addAll(data.getList());
                                if (page == 1) {
                                    adapter.setNewData(listdata);
                                } else {
                                    adapter.addData(listdata);
                                    adapter.loadMoreComplete();
                                }
                            } else {
                                if (page == 1) {
                                    noData.setVisibility(View.VISIBLE);
                                } else {
                                    adapter.loadMoreFail();
                                    ObjectUtils.toast(mcontext, response.getMsg());
                                }
                            }
                        }
                    }
            );
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }

    private void GetHeadImageData() {
        String address = ConstantsUrl.domain + "goods/ad/4";
        HttpUtils.get(address, null, new SortHeadThumbDataCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                adapter.removeHeaderView(header);
            }

            @Override
            public void onResponse(SortHeadThumbData response, int id) {
                String data = response.getData();
                if (data != null) {
                    ObjectUtils.photo2(getActivity(), data, (ImageView) header.findViewById(R.id.item_list_sort_dapai_img));
                    adapter.notifyDataSetChanged();
                }else {
                    adapter.removeHeaderView(header);
                }
            }
        });
    }
}
